import { Component } from 'vue-facing-decorator';
import { Button, Checkbox, Col, Form, Input, Row } from 'ant-design-vue';
import { computed, reactive, ref, unref } from 'vue';
import LoginFormTitle from './login.form.title.vue';
import { LoginFormAbs } from '@2/views/login/login.form.abs';
import { useMessage } from '@/hooks/web/useMessage';
import { Enums } from '@2/app/core/api/enums';
import { UserService } from '@2/app/core/ioc';
import { LoginFrom, LoginStateEnum } from '@2/typings/form.d';
import { buildUUID } from '@/utils/uuid';
import { useDesign } from '@/hooks/web/useDesign';

/**
 * @program: microservice-central-portal
 * @description: 平台用户登录入口
 * @author: baiHoo.chen
 * @create: 2022年5月24日
 **/
@Component({
  name: 'LoginForm',
  setup() {
    return { formRef: ref() };
  },
  components: {
    ACol: Col,
    ARow: Row,
    FormItem: Form.Item,
    InputPassword: Input.Password,
    Form,
    Input,
    Button,
    Checkbox,
    LoginFormTitle,
  },
})
export default class LoginForm extends LoginFormAbs {
  prefixCls: string = useDesign('login').prefixCls;
  loading = ref(false);
  captchaBase64 = ref('');
  formData = reactive<LoginFrom>({
    username: '',
    password: '',
    captcha: '',
    deviceId: '',
    rememberMe: false,
  });
  showed = computed(() => unref(this.getLoginState()) === LoginStateEnum.LOGIN);
  mounted() {
    this.refreshCaptcha();
  }
  resetPassword(): void {
    this.setLoginState(LoginStateEnum.RESET_PASSWORD);
  }
  /**
   * 获取图形验证码 事件函数
   */
  refreshCaptcha() {
    this.formData.deviceId = buildUUID();
    this.captchaBase64 = ref('/api' + Enums.RANDOM_CODE + `${this.formData.deviceId}`);
  }
  /**
   * 操作登录
   */
  async handleLogin() {
    const { notification } = useMessage();
    const data = await this.validForm(this.formRef);
    if (!data) return;
    try {
      this.loading = ref(true);
      const appUser = await UserService.login({
        ...data,
        deviceId: this.formData.deviceId,
        grant_type: 'password_code',
        mode: 'modal',
      });
      if (appUser) {
        notification.success({
          message: this.t('sys.login.loginSuccessTitle'),
          description: `${this.t('sys.login.loginSuccessDesc')}: ${appUser.realName}`,
          duration: 3,
        });
      }
    } finally {
      this.loading = ref(false);
    }
  }
}
